﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SiGeSIB.Data.Management;
using SiGeSIB.Data.Common;

namespace SiGeSIB.GUI.Common
{
	public partial class UAddressControl : UserControl
	{
		public UAddressControl()
		{
			InitializeComponent();
		}

		private Address _CurrentAddress;
		private Dictionary<string, Address> _Addresses;
		private bool _ReadOnly;
		private bool _Enabled;

		/// <summary>
		/// Dicionário de Endereços indexados pelo CEP
		/// </summary>
		public Dictionary<string, Address> Addresses
		{
			get { return _Addresses; }
			set
			{
				_Addresses = value;
			}
		}
		public new bool Enabled
		{
			get
			{
				return _Enabled;
			}
			set
			{
				_Enabled = value;

				_UpdateUIStatus();
			}
		}
		public bool ReadOnly
		{
			get
			{
				return _ReadOnly;
			}
			set
			{
				_ReadOnly = value;

				_UpdateUIStatus();
			}
		}

		public Address BuildAddress()
		{
			Address address = _CurrentAddress ?? new Address();

			address.Street = txtStreet.Text;
			address.Complement = txtComplement.Text;
			address.City = txtCity.Text;
			address.District = txtDistrict.Text;
			address.State = txtState.Text;
			address.CEP = mtbCEP.GetValue();

			return address;
		}
		public void FillAddress(Address address)
		{
			if (address != null)
			{
				txtComplement.Text = address.Complement;
			}

			_FillAddress(address, true);
			_CurrentAddress = address;
		}
		private void _FillAddress(Address address, bool writeCEP)
		{
			if (address == null)
				address = new Address();

			txtStreet.Text = address.Street;
			txtComplement.Text = address.Complement;
			txtCity.Text = address.City;
			txtDistrict.Text = address.District;
			txtState.Text = address.State;
			if (writeCEP)
				mtbCEP.Text = address.CEP;
		}
		private void _UpdateUIStatus()
		{
			lblCEP.Enabled = lblCity.Enabled =
				lblComplement.Enabled = lblDistrict.Enabled =
					lblState.Enabled = lblStreet.Enabled = _Enabled && !_ReadOnly;

			txtStreet.Enabled = txtDistrict.Enabled = txtCity.Enabled =
				txtState.Enabled = mtbCEP.Enabled = txtComplement.Enabled = Enabled;
			txtStreet.ReadOnly = txtDistrict.ReadOnly = txtCity.ReadOnly = 
				txtState.ReadOnly = mtbCEP.ReadOnly = txtComplement.ReadOnly = _ReadOnly;
		}

		private void mtbCEP_Leave(object sender, EventArgs e)
		{
			string CEP = mtbCEP.MaskedTextProvider.ToString(false, false);

			if (Addresses != null && Addresses.ContainsKey(CEP))
				_FillAddress(Addresses[CEP], false);
			else
				_FillAddress(null, false);
		}

		public void Clear()
		{
			_FillAddress(null, true);
			txtComplement.Text = null;
		}
	}
}
